package com.epalmpay.service.activity.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.mapper.ActivityBaseMapper;
import com.epalmpay.mapper.ActivityUnroutineRuleMapper;
import com.epalmpay.mapper.RedpackageMapper;
import com.epalmpay.service.thread.CheckRedpackageActivityRuleThread;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Logger;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;

import com.epalmpay.entity.Redpackage;
import com.epalmpay.entity.RedpackageUser;
import com.epalmpay.mapper.RedpackageUserMapper;
import com.epalmpay.service.activity.IActivityRedPackageService;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.member.IMemberService;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


@Service("redPackageUserService")
public class RedPackageUserServiceImpl implements IRedPackageUserService{

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource  
    private RedpackageUserMapper redpackageUserMapper;
	
	@Resource
	private IActivityRedPackageService activityredPackageService;
	@Resource
	RedpackageMapper redpackageMapper;
	@Resource
	private IMemberService memberService;

	@Resource(name="transactionManager")
	private DataSourceTransactionManager transactionManager;
	@Resource
	private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
	@Resource
	private ActivityBaseMapper activityBaseMapper;


	/***
	 * 单个发红包(手动控制事物)
	 * @param memberId
	 * @param redPackageId
	 * @param activityId
	 * @param getType
	 * @param memo
	 * @return
	 *     -1:红包已结束
	 *     -2:红包已领完
	 *     -3:过了结束领取时间
	 *     -4:超过最大领取张数
	 *     1:成功
	 * @throws Exception
	 */
	public int sendOneMemberRedPackage(Long memberId,Long redPackageId,Long activityId,Integer getType,String memo, Long relatedTradeOfflineId) throws Exception{

		//DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		//def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		//TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		Redpackage redpackage = redpackageMapper.selectByPrimaryKey(redPackageId);
		StringBuffer sb = new StringBuffer();
		Redpackage redpackageUpdate = new Redpackage();
		redpackageUpdate.setId(redpackage.getId());

		if( redpackage.getStatus()== ActivityEnum.RedPackageStatus.Over.getType()) {
			logger.info(sb.append("红包状态:").append(ActivityEnum.RedPackageStatus.Over.getName()));
			//transactionManager.rollback(status);
			return -1;
		}
		if( redpackage.getStatus()== ActivityEnum.RedPackageStatus.FinishedGet.getType()) {
			logger.info(sb.append("红包状态:").append(ActivityEnum.RedPackageStatus.FinishedGet.getName()));
			//throw new ApplicationException("红包已结束");
			//transactionManager.rollback(status);
			return -2;
		}

		if(redpackage.getValidTimeType()==1){

			String beginTime = DateUtil.fomatDate(new Date(), DateUtil.sdfDay);
			String  endTime = DateUtil.fomatDate(redpackage.getEndGetTime(), DateUtil.sdfDay);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			Date bt = sdf.parse(beginTime);
			Date et=sdf.parse(endTime);

			if(redpackage.getValidTimeType() == ActivityEnum.CouponValidType.FixedTime.getType() && (bt).compareTo(et)>0){
				logger.info(sb.append("红包ID:").append(redPackageId).append("过了结束领取时间!"));
				//transactionManager.rollback(status);
				return -3;
			}
		}else{
			if(redpackage.getValidTimeType() == ActivityEnum.CouponValidType.FixedTime.getType() && (new Date()).compareTo(redpackage.getEndGetTime())>0){
				logger.info(sb.append("红包ID:").append(redPackageId).append("过了结束领取时间!"));
				//transactionManager.rollback(status);
				return -3;
			}
		}

		//检查最大数量(除了不限的情况)
		int count = redpackageUserMapper.selectSendRedpackageCount(memberId,redPackageId);
		redpackage.setAmountPeruser(redpackage.getAmountPeruser()==null?0:redpackage.getAmountPeruser());
		if(redpackage.getAmountPeruser() != -1 && count >= redpackage.getAmountPeruser()) {
			logger.info(sb.append("超过最大领取张数"));
			//transactionManager.rollback(status);
			//throw new ApplicationException("红包超过最大领取张数！");
			return -4;
		}

		try {
			//redpackageUpdate.setTotalCount(redpackageUpdate.getTotalCount()==null?0:redpackageUpdate.getTotalCount());
			redpackageUpdate.setSendCount(redpackage.getSendCount()==null?0:redpackage.getSendCount());
			redpackageUpdate.setId(redPackageId);
			redpackageUpdate.setGmtModified(new Date());
			redpackageUpdate.setSendCount(redpackageUpdate.getSendCount() + 1);//已发数量加1
			if(redpackageUpdate.getSendCount()==redpackage.getTotalCount()) {
				redpackageUpdate.setStatus(ActivityEnum.RedPackageStatus.FinishedGet.getType());

				if(redpackage.getPurposeType().equals(ActivityEnum.PurposeType.UnRoutine.getType())) {
					logger.debug(">>>>>>红包已发完，开始异步检查使用本红包的动态活动<<<<<<");
					new Thread(new CheckRedpackageActivityRuleThread(redPackageId, activityUnroutineRuleMapper, activityBaseMapper)).start();
				}
			}
			redpackageMapper.updateByPrimaryKeySelective(redpackageUpdate);
			//插入会员红包表
			RedpackageUser redpackageUser = new RedpackageUser();
			redpackageUser.setGmtCreate(new Date());
			redpackageUser.setGmtModified(new Date());
			redpackageUser.setMemberId(memberId);
			//取有效期
			Date validTime = null;
			if(redpackage.getValidTimeType() == ActivityEnum.CouponValidType.FixedTime.getType()){
				validTime = redpackage.getEndGetTime();
			}
			else if(redpackage.getValidTimeType() == ActivityEnum.CouponValidType.ValidAfterGet.getType()){
				validTime = DateUtil.getAfterDay(redpackage.getAftergetValidtime());
			}
			redpackageUser.setValidTime(validTime);
			redpackageUser.setRedpackageId(redPackageId);
			redpackageUser.setGetStatus(ActivityEnum.RedpackageGetStatus.Received.getType());
			redpackageUser.setActivityId(activityId);
			redpackageUser.setGetType(getType);
			redpackageUser.setGroupId(redpackage.getGroupId());
			redpackageUser.setRemark(memo);
			redpackageUser.setTradeOfflineId(relatedTradeOfflineId);
			redpackageUserMapper.insert(redpackageUser);

			//transactionManager.commit(status);
		}catch (Exception e) {
			//transactionManager.rollback(status);
			logger.error("commit error", e);
			e.printStackTrace();
			throw e;
		}
		return 1;
	}

	//给单个会员发红包
	public int sendOneMemberRedPackage(Long memberId,Long redPackageId,Long activityId,Integer getType, Long relatedTradeOfflineId) throws Exception{
		return sendOneMemberRedPackage(memberId,redPackageId,activityId,getType,null,relatedTradeOfflineId);
	}

}
		
